#include <Primative.h>
#include <math.h>
#include <iostream>

using namespace std;

float Sphere::intersect(const Ray& ray, float& distance)
{
#if 0
  Float3 v = ray.Origin - this->Origin;

  float b = -Float3::Dot(ray.Direction, v);
  float det = b * b - Float3::Dot(v, v) + Radius * Radius;

  if(det > 0.0f)
  {
    det = sqrtf(det);

    float i1 = b - det;
    float i2 = b + det;

    if(i2 > 0.0f && i2 < distance && i2 < i1)
    {
      distance = i2;
      return 1.0f;
    }
    else if(i1 > 0.0f && i1 < distance)
    {
      distance = i1;
      return 1.0f;
    }
#if 0
    if(i2 > 0.0f)
    {
      if(i1 < 0.0f && i2 < distance)
      {
        distance = i2;
        return 1.0f;
      }
      else if(i1 < distance)
      {
        distance = i1;
        return 1.0f;
      }
    }
#endif
  }

  return 0.0f;

#else
  Float3 v = ray.Origin - this->Origin;
  float b = -Float3::Dot(v, ray.Direction);
  float det = (b * b) - Float3::Dot(v, v) + Radius * Radius;

  if(det > 0.0f)
  {
    det = sqrtf(det);
    float i1 = b - det;
    float i2 = b + det;

    if(i2 > 0.0f)
    {
      if(i1 < 0.0f && i2 < distance)
      {
        distance = i2;
        return -1.0f;
      }
      else if(i1 < distance)
      {
        distance = i1;
        return 1.0f;
      }
    }
  }

  return 0.0f;
#endif
}

Plane::Plane(const Float3& _p0, const Float3& p1, const Float3& p2) :
  p0(_p0)
{
  Float3 v1 = p1 - p0;
  Float3 v2 = p2 - p0;

  Normal = Float3::Cross(v1, v2).normalize();
}

float Plane::intersect(const Ray& ray, float& distance)
{
  float denominator = Float3::Dot(ray.Direction, Normal);

  if(denominator == 0.0f)
  {
    return 0.0f;
  }

  else
  {
    float newDist = Float3::Dot(p0 - ray.Origin, Normal) /  denominator;

    if(newDist > 0.0f && newDist < distance)
    {
      distance = newDist;
      return 1.0f;
    }
  }

  if(distance < 0.0f)
  {
    return 0.0f;
  }

  return 0.0f;

}


